package com.beiye.drivertransport.fragment;


import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.SubActivity.SpecifiedLearningCourseDetailsActivity;
import com.beiye.drivertransport.adapter.PopWindowApt;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.bean.SpecifiedLearningBean;
import com.beiye.drivertransport.http.Login;
import com.beiye.drivertransport.utils.CameraCanUseUtils;
import com.beiye.drivertransport.utils.CustomProgressDialog;
import com.beiye.drivertransport.utils.LogUtils;
import com.beiye.drivertransport.utils.MessageEvent;
import com.beiye.drivertransport.utils.TiShiDialog;
import com.beiye.drivertransport.utils.ToastUtil;
import com.beiye.drivertransport.utils.UserManger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
//指定学习（这种界面暂时没有用到）
public class SpecifiedLearningFragment extends TwoBaseFgt {


    ExpandableListView specified_lv;

    TextView tv_specified_learning;

    View empty_view;

    TextView img_specified_learning;
    ArrayList<LoginUserBean.DataBean.CurUserOrgBean> cusList = new ArrayList<>();
    private List<SpecifiedLearningBean.RowsBean> ParentList = new ArrayList<>();
    private List<List<SpecifiedLearningBean.RowsBean.ListCourseBean>> childrenList = new ArrayList<>();
    private MyExpandableListViewAdapter adapter;
    private PopupWindow mPopWindow;
    private PopWindowApt popWindowApt;
    Map<SpecifiedLearningBean.RowsBean, List<SpecifiedLearningBean.RowsBean.ListCourseBean>> dataset = new HashMap<>();
    private CustomProgressDialog dialog;


    @Override
    public int getLayoutId() {
        return R.layout.fragment_specified_learning;
    }

    public void onClick(View view) {
        if (view.getId() == R.id.tv_specified_learning) {//弹框，用户选择所属公司.选择后请求服务器更新通知内容
            //          Toast.makeText(getContext(),"选择公司",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void initData() {
        specified_lv = (ExpandableListView) getActivity().findViewById(R.id.specified_expandablelistview);
        tv_specified_learning = (TextView) getActivity().findViewById(R.id.tv_specified_learning);
        empty_view = (View) getActivity().findViewById(R.id.empty_view);
        img_specified_learning = (TextView) getActivity().findViewById(R.id.img_specified_learning);

        tv_specified_learning.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popWindowApt == null || popWindowApt.getCount() == 1) {
                    return;
                } else {
                    showPopupWindow();
                }
            }
        });

        //注册EventBus
        EventBus.getDefault().register(this);
        initUi();
//        LoginUserBean userInfo = UserManger.getUserInfo();
//        initCompany(userInfo);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(MessageEvent event) {
        LoginUserBean userInfo = event.getUserInfo();
        initCompany(userInfo);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//反注册EventBus
    }

    @Override
    public void requestData() {

//        SharedPreferences spp = getActivity().getSharedPreferences("orgId11",
//                Context.MODE_PRIVATE);
//        String orgId = spp.getString("orgId", "");
//        SharedPreferences sp = getActivity().getSharedPreferences("readInterval1",
//                Context.MODE_PRIVATE);
//        int readInterval = sp.getInt("readInterval", 0);
//
//        initUiData(orgId, readInterval);
        LoginUserBean userInfo = UserManger.getUserInfo();
        initCompany(userInfo);
    }

    private void initCompany(LoginUserBean userInfo) {
        //  LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        if (data == null) {
            return;
        }
        String userId = data.getUserId();
        LogUtils.e("userId", userId);//6E7119CD-699B-49A2-A0B0-045D0BF7B8C0
        List<LoginUserBean.DataBean.CurUserOrgBean> curuserOrglist = data.getCur_userOrg();

        if (curuserOrglist.size() == 0) {
            img_specified_learning.setVisibility(View.INVISIBLE);
            return;
        }
        cusList.clear();
        for (int i = 0; i < curuserOrglist.size(); i++) {
            if (curuserOrglist.get(i).getMark() != 2) {
                cusList.add(curuserOrglist.get(i));
            }
        }
        String orgName = cusList.get(0).getOrgName();
        String orgId = cusList.get(0).getOrgId();
        int minPer = cusList.get(0).getMinPer();
        int readInterval = cusList.get(0).getReadInterval();
        int mark = cusList.get(0).getMark();
        SharedPreferences spp = getActivity().getSharedPreferences("orgId11",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = spp.edit();
        edit.putInt("minPer", minPer);
        edit.commit();
        //存储一份readInterval文件
        SharedPreferences sp = getActivity().getSharedPreferences("readInterval1",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("readInterval", readInterval);
        editor.commit();
        SharedPreferences sppp = getActivity().getSharedPreferences("Mark1", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor2 = sppp.edit();
        editor2.putInt("Mark", mark);
        editor2.commit();
        tv_specified_learning.setText(orgName);
        //    requestData();
        initUiData(orgId, readInterval);
        //      readintervalData(adId);
        popWindowApt = new PopWindowApt(getActivity(), cusList, R.layout.popwindow_item_layout);

        if (popWindowApt.getCount() == 1) {
            img_specified_learning.setVisibility(View.INVISIBLE);
        } else {
            img_specified_learning.setVisibility(View.VISIBLE);
        }

    }

    private void showPopupWindow() {
        //设置contentView
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popwindow_layout, null);
        mPopWindow = new PopupWindow(contentView,
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
        //设置各个控件的点击响应
        ListView lv_company = (ListView) contentView.findViewById(R.id.lv_company);
        lv_company.setAdapter(popWindowApt);
        mPopWindow.showAtLocation(tv_specified_learning, Gravity.CENTER, 0, 0);
//        mPopWindow.setAnimationStyle(R.style.contextMenuAnim);
//        mPopWindow.showAsDropDown(tv_specified_learning);
        lv_company.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if (popWindowApt != null) {

                    String orgName = popWindowApt.getItem(position).getOrgName();
                    String orgId = popWindowApt.getItem(position).getOrgId();
                    int minPer = popWindowApt.getItem(position).getMinPer();
                    int readInterval = popWindowApt.getItem(position).getReadInterval();
                    int mark = popWindowApt.getItem(position).getMark();
                    SharedPreferences spp = getActivity().getSharedPreferences("orgId11",
                            Context.MODE_PRIVATE);
                    SharedPreferences.Editor edit = spp.edit();
                    edit.putInt("minPer", minPer);
                    edit.commit();
                    //存储一份readInterval文件
                    SharedPreferences sp = getActivity().getSharedPreferences("readInterval1",
                            Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putInt("readInterval", readInterval);
                    editor.commit();
                    SharedPreferences sppp = getActivity().getSharedPreferences("Mark1", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor2 = sppp.edit();
                    editor2.putInt("Mark", mark);
                    editor2.commit();
                    mPopWindow.dismiss();
                    tv_specified_learning.setText(orgName);
                    //  requestData();
                    initUiData(orgId, readInterval);
                    //                  readintervalData(adId);

                }
            }
        });
    }
//    //进入岗前培训时界面前调一下接口
//    public void readintervalData(String adId)
//    {
//        OkGo.get(AppInterfaceConfig.BASE_URL+"sys/config/query/"+adId)     // 请求方式和请求url
//                .tag(this)                       // 请求的 tag, 主要用于取消对应的请求
//                .execute(new StringCallback() {
//                    @Override
//                    public void onSuccess(String result, Call call, Response response) {
//
//                        ReadIntervalBean readIntervalBean =JSON.parseObject(result, ReadIntervalBean.class);
//
//                        ReadIntervalBean.DataBean data = readIntervalBean.getData();
//                        int   readInterval = data.getReadInterval();
//                        //存储一份readInterval文件
//                        SharedPreferences sp = getActivity().getSharedPreferences("readInterval",
//                                Context.MODE_PRIVATE);
//                        SharedPreferences.Editor editor = sp.edit();
//                        editor.putInt("readInterval", readInterval);
//                        editor.commit();
//                    }
//                });
//    }

    @Override
    public void onResume() {
        super.onResume();
        SharedPreferences spp = getActivity().getSharedPreferences("orgId11",
                Context.MODE_PRIVATE);
        String orgId = spp.getString("orgId", "");
        SharedPreferences sp = getActivity().getSharedPreferences("readInterval1",
                Context.MODE_PRIVATE);
        int readInterval = sp.getInt("readInterval", 0);

        initUiData(orgId, readInterval);
    }

    public void initUiData(String orgId, int readInterval) {

        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        if (data == null) {
            return;
        }
        String userId = data.getUserId();

//        //存储一份readInterval文件
//        SharedPreferences sp = getActivity().getSharedPreferences("readInterval",
//                Context.MODE_PRIVATE);
//        int  readInterval = sp.getInt("readInterval", 0);
        SharedPreferences spp = getActivity().getSharedPreferences("orgId11",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = spp.edit();
        edit.putString("orgId", orgId);
        edit.commit();
        new Login().getSpecifiedLearning(orgId, userId, readInterval, 1, 1, 1000, this, 1);

    }

    @Override
    public void onSuccess(String result, Call call, Response response, int what) {
        if (what == 1) {

            SpecifiedLearningBean specifiedLearningBean = JSON.parseObject(result, SpecifiedLearningBean.class);
            List<SpecifiedLearningBean.RowsBean> rows = specifiedLearningBean.getRows();
            ParentList.clear();
            dataset.clear();
            ParentList.addAll(rows);
            for (int i = 0; i < ParentList.size(); i++) {
                List<SpecifiedLearningBean.RowsBean.ListCourseBean> listCourse = ParentList.get(i).getListCourse();
                dataset.put(ParentList.get(i), listCourse);
            }
            adapter = new MyExpandableListViewAdapter(getContext(), ParentList, dataset);
            specified_lv.setAdapter(adapter);


        }
//        else if (what == 2) {
//            if(!CameraCanUseUtils.isCameraCanUse()) {
//                ToastUtil.showShortToast(getActivity(),"请到手机设置界面里找驾运宝允许开启照相");
//                dialog.dismiss();
//                return;
//            }
//
//            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
//            int code = checkBean.getCode();
//            String msg = checkBean.getMsg();
//            if (code == 0) {
//
//                //存储一份readInterval文件
//                SharedPreferences spp = getActivity().getSharedPreferences("prejobTraingtcSn",
//                        Context.MODE_PRIVATE);
//                int tcSn = spp.getInt("tcSn", 0);
//                int otcSn = spp.getInt("otcSn", 0);
//                Bundle bundle = new Bundle();
//                bundle.putInt("tcsn", tcSn);
//                bundle.putInt("otcSn", otcSn);
//                SharedPreferences sp = getActivity().getSharedPreferences("readInterval",
//                        Context.MODE_PRIVATE);
//                int readInterval = sp.getInt("readInterval", 0);
//                bundle.putInt("readInterval", readInterval);
//                //存储一份orgId文件
//                SharedPreferences sppp = getActivity().getSharedPreferences("orgId11",
//                        Context.MODE_PRIVATE);
//                String orgId = sppp.getString("orgId", "");
//                bundle.putString("orgId", orgId);
//                startActivity(SpecifiedLearningCourseDetailsActivity.class, bundle);
//
//           //     Toast.makeText(getActivity(), tcSn + "", Toast.LENGTH_SHORT).show();
//            }
//            dialog.dismiss();
//        }
        super.onSuccess(result, call, response, what);
    }

    //    @Override
//    public void onError(String result, Call call, Response response, int what) {
//
//        if(what==2)
//        {
//            dialog.dismiss();
//            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
//            //     int code = checkBean.getCode();
//            String msg = checkBean.getMsg();
//            LemonHello.getSuccessHello("提示", msg)
//                    .addAction(new LemonHelloAction("我知道啦", new LemonHelloActionDelegate() {
//                        @Override
//                        public void onClick(LemonHelloView helloView, LemonHelloInfo helloInfo, LemonHelloAction helloAction) {
//                            helloView.hide();
//                        }
//                    }))
//                    .show(getActivity());
//
//        }
//
//        super.onError(result, call, response, what);
//    }
    @Override
    public void onUserVisible() {

    }

    private void initUi() {

        specified_lv.setGroupIndicator(null);//去掉箭头
        specified_lv.setEmptyView(empty_view);
        specified_lv.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int groupPosition, int childPosition, long l) {

                SharedPreferences sp1 = getActivity().getSharedPreferences("Mark1", Context.MODE_PRIVATE);
                int mark = sp1.getInt("Mark", 1);
                if (mark == 0) {
                    TiShiDialog.Builder builder1 = new TiShiDialog.Builder(getActivity());
                    builder1.setMessage("您已被企业管理员禁用,请联系企业管理员");
                    builder1.setTitle("提示:");
                    builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            //设置你的操作事项
                        }
                    });
                    builder1.create().show();

                } else {
                    if (!CameraCanUseUtils.isCameraCanUse()) {

                        ToastUtil.showShortToast(getActivity(), "请到手机设置界面里找驾运宝允许开启照相");
                    } else {
                        if (dataset.get(ParentList.get(groupPosition)).get(childPosition).getStudyState() == 0) {
                            showLoadingDialog("正在加载");

                            int tcSn = dataset.get(ParentList.get(groupPosition)).get(childPosition).getTcSn();
                            int otcSn = dataset.get(ParentList.get(groupPosition)).get(childPosition).getSn();
                            Bundle bundle = new Bundle();
                            bundle.putInt("tcsn", tcSn);
                            bundle.putInt("otcSn", otcSn);
                            SharedPreferences sp = getActivity().getSharedPreferences("readInterval1",
                                    Context.MODE_PRIVATE);
                            int readInterval = sp.getInt("readInterval", 0);
                            bundle.putInt("readInterval", readInterval);
                            //存储一份orgId文件
                            SharedPreferences sppp = getActivity().getSharedPreferences("orgId11",
                                    Context.MODE_PRIVATE);
                            String orgId = sppp.getString("orgId", "");
                            int minPer = sppp.getInt("minPer", 0);
                            bundle.putInt("minPer", minPer);
                            bundle.putString("orgId", orgId);
                            startActivity(SpecifiedLearningCourseDetailsActivity.class, bundle);

                        } else if (dataset.get(ParentList.get(groupPosition)).get(childPosition).getStudyState() == 1) {
                            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(getContext());
                            builder1.setMessage("该课程已学习");
                            builder1.setTitle("提示:");
                            builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();

                                    //设置你的操作事项
                                }
                            });
                            builder1.create().show();

                        }
                    }
                }
                //    initcoursesupermaketCheckData(tcSn,otcSn);
                return true;
            }
        });

    }

    //    //校验岗前培训课程是否学过
//    private void initcoursesupermaketCheckData(int tcSn , int otcSn) {
//        LoginUserBean userInfo = UserManger.getUserInfo();
//        String userId = userInfo.getUserId();
//        //存储一份readInterval文件
//        SharedPreferences sp = getActivity().getSharedPreferences("readInterval",
//                Context.MODE_PRIVATE);
//        int readInterval = sp.getInt("readInterval", 0);
//        //存储一份tcSn文件
//        SharedPreferences spp = getActivity().getSharedPreferences("prejobTraingtcSn",
//                Context.MODE_PRIVATE);
//        SharedPreferences.Editor editor = spp.edit();
//        editor.putInt("tcSn", tcSn);
//        editor.putInt("otcSn",otcSn);
//        editor.commit();
//        dialog = CustomProgressDialog.show(getActivity(), "", true, null);
//        new Login().getPreJobTrainingandcoursesupermaketCheck(userId, tcSn, readInterval, this, 2);
//
//    }
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        return false;
    }

    private class MyExpandableListViewAdapter extends BaseExpandableListAdapter {

        private Context context;
        private List<SpecifiedLearningBean.RowsBean> ParentList;
        private Map<SpecifiedLearningBean.RowsBean, List<SpecifiedLearningBean.RowsBean.ListCourseBean>> dataset;

        public MyExpandableListViewAdapter(Context context, List<SpecifiedLearningBean.RowsBean> ParentList, Map<SpecifiedLearningBean.RowsBean, List<SpecifiedLearningBean.RowsBean.ListCourseBean>> dataset) {
            this.context = context;
            this.ParentList = ParentList;
            this.dataset = dataset;
        }

        //  获得某个父项的某个子项
        @Override
        public Object getChild(int parentPos, int childPos) {
            return dataset.get(ParentList.get(parentPos)).get(childPos);
        }

        //  获得父项的数量
        @Override
        public int getGroupCount() {
            return dataset.size();
        }

        //  获得某个父项的子项数目
        @Override
        public int getChildrenCount(int parentPos) {
            return dataset.get(ParentList.get(parentPos)).size();
        }

        //  获得某个父项
        @Override
        public Object getGroup(int parentPos) {
            return dataset.get(ParentList.get(parentPos));
        }

        //  获得某个父项的id
        @Override
        public long getGroupId(int parentPos) {
            return parentPos;
        }

        //  获得某个父项的某个子项的id
        @Override
        public long getChildId(int parentPos, int childPos) {
            return childPos;
        }

        //  按函数的名字来理解应该是是否具有稳定的id，这个方法目前一直都是返回false，没有去改动过
        @Override
        public boolean hasStableIds() {
            return false;
        }

        //  获得父项显示的view
        @Override
        public View getGroupView(int parentPos, boolean b, View view, ViewGroup viewGroup) {
            if (view == null) {
                LayoutInflater inflater = (LayoutInflater) getActivity()
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflater.inflate(R.layout.parent_item, null);
            }
            view.setTag(R.layout.parent_item, parentPos);
            view.setTag(R.layout.child_item, -1);
            ImageView img_parent = (ImageView) view.findViewById(R.id.img_parent);
            TextView parent_line = (TextView) view.findViewById(R.id.parent_line);
            TextView tv_title = (TextView) view.findViewById(R.id.tv_parent);
            TextView tv_date = (TextView) view.findViewById(R.id.tv_parent2);
            LinearLayout re_nodata = (LinearLayout) view.findViewById(R.id.re_nodata);//子类无数据

            if (ParentList != null && parentPos < ParentList.size()) {
                tv_title.setText(ParentList.get(parentPos).getPlanName());
                long beginDate = ParentList.get(parentPos).getBeginDate();
                long endDate = ParentList.get(parentPos).getEndDate();
                //mill为你龙类型的时间戳
                Date date1 = new Date(beginDate);
                Date date2 = new Date(endDate);
                String begin = "";
                String end = "";
                try {
                    //yyyy表示年MM表示月dd表示日
                    //yyyy-MM-dd是日期的格式，比如2015-12-12如果你要得到2015年12月12日就换成yyyy年MM月dd日
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                    //进行格式化
                    begin = sdf.format(date1);
                    end = sdf.format(date2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                tv_date.setText(begin + "--" + end);
                LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) parent_line.getLayoutParams(); //取控件textView当前的布局参数
                if (b)//判断展开
                {

                    if (ParentList.get(parentPos).getListCourse().size() == 0) {
                        re_nodata.setVisibility(View.VISIBLE);
                    }
                    img_parent.setImageResource(R.mipmap.jianhao);
                    linearParams.height = 3;// 控件的高强制设成3
                    parent_line.setLayoutParams(linearParams);

                } else {
                    re_nodata.setVisibility(View.GONE);
                    img_parent.setImageResource(R.mipmap.jiahao);
                    linearParams.height = 13;// 控件的高强制设成16
                    parent_line.setLayoutParams(linearParams);
                }
            }

            return view;
        }

        //  获得子项显示的view
        @Override
        public View getChildView(int parentPos, int childPos, boolean b, View view, ViewGroup viewGroup) {
            if (view == null) {
                LayoutInflater inflater = (LayoutInflater) getActivity()
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflater.inflate(R.layout.child_item, null);
            }
            view.setTag(R.layout.parent_item, parentPos);
            view.setTag(R.layout.child_item, childPos);
            TextView tv_ttName = (TextView) view.findViewById(R.id.tv_child);
            TextView tv_courseName = (TextView) view.findViewById(R.id.tv_child2);
            TextView tv_courseLength = (TextView) view.findViewById(R.id.tv_child3);
            ImageView tv_studyState = (ImageView) view.findViewById(R.id.tv_child4);
            tv_ttName.setText(dataset.get(ParentList.get(parentPos)).get(childPos).getTtName());
            tv_courseName.setText(dataset.get(ParentList.get(parentPos)).get(childPos).getCourseName());
            tv_courseLength.setText("课程时长:" + dataset.get(ParentList.get(parentPos)).get(childPos).getCourseLength() + "分钟");
            if (dataset.get(ParentList.get(parentPos)).get(childPos).getStudyState() == 0) {
                tv_studyState.setImageResource(R.mipmap.wxx);
            } else if (dataset.get(ParentList.get(parentPos)).get(childPos).getStudyState() == 1) {
                tv_studyState.setImageResource(R.mipmap.yxx);

            }


            return view;
        }

        //  子项是否可选中，如果需要设置子项的点击事件，需要返回true
        @Override
        public boolean isChildSelectable(int i, int i1) {

            return true;
        }
    }
}
